package com.patrol.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patrol.dao.RiskInfoDao;
import com.patrol.dao.SendInfoDao;
import com.patrol.dao.WorkDao;
import com.patrol.dao.WrjVideoDao;
import com.patrol.pojo.*;
import com.patrol.service.UserService;
import com.patrol.service.WorkerService;
import com.patrol.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "工作接口")
@RestController
@RequestMapping("/api/worker")
@CrossOrigin
public class WorkerController {

    @Value("${patrol.path.upload}")
    private String uploadPath;

    @Resource
    private WorkerService workerService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private RiskInfoDao riskInfoDao;

    @Resource
    private SendInfoDao sendInfoDao;

    @Resource
    private WorkDao workDao;


//    /**
//     * 用户打卡上班
//     * @param userId
//     * @return
//     */
//    @ApiOperation(value = "用户打卡上班")
//    @GetMapping("/signInWork")
//    public Result signWork(@PathVariable String userId){
//        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        workerService.signWork(userId, df.format(new Date()));
//        return workerService.signWork(userId, df.format(new Date())) ? Result.ok() : Result.fail();
//    }

    @GetMapping("/selectAllWorkers")
    public Result selectAllWorkers() {
        List<Worker> list = workerService.selectAllWorkers();
        return Result.ok(list);
    }

    @ApiOperation(value = "用户上传实时位置")
    @GetMapping("/uploadLocation")
    public Result uploadLocation(@RequestParam(value = "userId") Integer userId,
                                 @RequestParam(value = "latitudeX") Double latitudeX,
                                 @RequestParam(value = "longitudeY") Double longitudeY){
        User byId = userService.getById(userId);
        if (byId.getIsAssigned()==1){
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String locationRedisKey = "location:" + userId + ":" + df.format(new Date());
            redisTemplate.opsForHash().put(locationRedisKey,"latitudeX",latitudeX);
            redisTemplate.opsForHash().put(locationRedisKey, "longitudeY", longitudeY);

            //保存用户巡更轨迹
            String userLocusRedisKey = "userlocus:" + userId;
            redisTemplate.opsForList().leftPush(userLocusRedisKey, locationRedisKey);

            //更新巡更人员现在的位置
            String userNowAtRedisKey = "userNowAt:" + userId;
            redisTemplate.opsForHash().put(userNowAtRedisKey,"latitudeX",latitudeX);
            redisTemplate.opsForHash().put(userNowAtRedisKey, "longitudeY", longitudeY);
            return Result.ok(200);
        }
        return Result.fail();
    }

    @ApiOperation(value = "用户开始一次巡更阶段")
    @GetMapping("/onceStartXGLX//{userId}")
    public Result onceStartXGLX(@PathVariable Integer userId) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = df.format(new Date());
        workDao.insertXGLX(userId, startTime);
        return Result.ok();
    }

    @ApiOperation(value = "用户结束一次巡更阶段")
    @GetMapping("/onceOverXGLX//{userId}")
    public Result onceOverXGLX(@PathVariable Integer userId) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String overTime = df.format(new Date());
        Integer id = workDao.selectXGLXId(userId);
        workDao.insertXGLXOverTime(overTime, id);

        String startTime = workDao.selectStartTime(userId);
        String userLocusRedisKey = "userlocus:" + userId;
        List list = redisTemplate.opsForList().range(userLocusRedisKey,0,-1);

        String userXGLXRedisKey = "userlocus:" + userId + ":" + startTime + ":" + overTime;
        for (int i=0;i<list.size();i++){
            redisTemplate.opsForList().leftPush(userXGLXRedisKey, list.get(i));
        }
        redisTemplate.delete(userLocusRedisKey);

        workerService.updateXGLXSign(userId);
        String s1 = "userNowAt:" + userId;
        redisTemplate.delete(s1);

        int num = workerService.selectRWLCNumById(userId);

        DateFormat df11 = new SimpleDateFormat("yyyy-MM-dd");
        Integer kqTableId = workerService.selectUserToday(userId,df11.format(new Date()));
        if(null != kqTableId){
            workerService.updateUserKQTJ(userId,num);
        }

        return Result.ok();
    }

//    @ApiOperation(value = "查询巡更人员本次的巡更路线")
//    @GetMapping("/uploadLocation/{userId}")
//    public Result uploadLocation(@PathVariable Integer userId){
//        String userLocusRedisKey = "userlocus:" + userId;
//        List list = redisTemplate.opsForList().range(userLocusRedisKey,0,-1);
//        System.out.println(list);
//        List<Map<String, Object>> list1 = new ArrayList<>();
//        for (int i=0;i<list.size();i++){
//            Object latitudeX = redisTemplate.opsForHash().get(list.get(i), "latitudeX");
//            Object longitudeY = redisTemplate.opsForHash().get(list.get(i), "longitudeY");
//            String o = (String) list.get(i);
//            String time = o.replace("location:" + userId + ":", "");
//            Map<String, Object> map = new HashMap<>();
//            map.put("latitudeX", latitudeX);
//            map.put("longitudeY", longitudeY);
//            map.put("time", time);
//            list1.add(map);
//        }
//        return Result.ok(list1);
//    }

    @ApiOperation(value = "巡更人员查询某一个历史巡更录像")
    @GetMapping("/selectOneXGHistory")
    public Result selectXGHistory(@RequestParam(value = "userId") Integer userId,
                                  @RequestParam(value = "startTime") String startTime,
                                  @RequestParam(value = "overTime") String overTime){
        String s1 = "userlocus:" + userId + ":" + startTime + ":" + overTime;
        List<String> list = redisTemplate.opsForList().range(s1,0,-1);
        List<Map<String, Object>> list1 = new ArrayList<>();

        for (int j=0;j<list.size();j++){
            System.out.println(list.get(j));
            Object latitudeX = redisTemplate.opsForHash().get(list.get(j), "latitudeX");
            Object longitudeY = redisTemplate.opsForHash().get(list.get(j), "longitudeY");
            String o = (String) list.get(j);
            String time = o.replace("location:" + userId + ":", "");
            Map<String, Object> m1 = new HashMap<>();
            m1.put("latitudeX", latitudeX);
            m1.put("longitudeY", longitudeY);
            m1.put("time", time);
            list1.add(m1);
        }
        return Result.ok(list1);
    }

    @ApiOperation(value = "巡更人员查询历史巡更录像")
    @GetMapping("/selectXGHistory/{userId}")
    public Result selectXGHistory(@PathVariable Integer userId){
        List<Xglx> xglxes = workDao.selectXGHistory(userId);
        Map<Integer, List> mmm = new HashMap<>();
        List<List> list2 = new ArrayList<>();

        for (int i=0;i<xglxes.size();i++){
            String s1 = "userlocus:" + userId + ":" + xglxes.get(i).getStartTime() + ":" + xglxes.get(i).getOverTime();
            List<String> list = redisTemplate.opsForList().range(s1,0,-1);
            List<Map<String, Object>> list1 = new ArrayList<>();

            Map<String, Object> timeMap = new HashMap<>();
            timeMap.put("startTime", xglxes.get(i).getStartTime());
            timeMap.put("overTime", xglxes.get(i).getOverTime());
            list1.add(timeMap);
            System.out.println(list);
            for (int j=0;j<list.size();j++){
                System.out.println(list.get(j));
                Object latitudeX = redisTemplate.opsForHash().get(list.get(j), "latitudeX");
                Object longitudeY = redisTemplate.opsForHash().get(list.get(j), "longitudeY");
                String o = (String) list.get(j);
                String time = o.replace("location:" + userId + ":", "");
                Map<String, Object> m1 = new HashMap<>();
                m1.put("latitudeX", latitudeX);
                m1.put("longitudeY", longitudeY);
                m1.put("time", time);
                list1.add(m1);
            }
            list2.add(list1);
        }

        System.out.println(list2);
        return Result.ok(list2);
    }

    @ApiOperation(value = "电脑端查看正在巡更的人员实时定位")
    @GetMapping("/selectUserNowLocation")
    public Result selectUserNowLocation(){
        List<Integer> list = workerService.selectNowXGUser();
        if (list.isEmpty()){
           return Result.fail();
        }

        List<Map<String, Object>> list1 = new ArrayList<>();
        for (int i=0;i<list.size();i++){
            Map<String, Object> map = new HashMap<>();
            String userNowAtRedisKey = "userNowAt:" + list.get(i);
            Object latitudeX = redisTemplate.opsForHash().get(userNowAtRedisKey, "latitudeX");
            Object longitudeY = redisTemplate.opsForHash().get(userNowAtRedisKey, "longitudeY");
            map.put("userId", list.get(i));
            map.put("realName", userService.getById(list.get(i)).getRealName());
            map.put("latitudeX", latitudeX);
            map.put("longitudeY", longitudeY);
            list1.add(map);
        }
//        Map<String, Object> map = new HashMap<>();
////        map.put("userSize", list.size());
//        list1.add(map);
        return Result.ok(list1);
    }

    @ApiOperation(value = "用户发送风险信息")
    @GetMapping("/sendRiskInfo")
    public Result uploadLocation(@RequestParam(value = "userId") Integer userId,
                                 @RequestParam(value = "message") String message) {
        Result result = new Result();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        User user = userService.getById(userId);
        String realName = user.getRealName();
        Integer insert = riskInfoDao.insertRiskInfo(userId, realName, message, df.format(new Date()),1);
        if (insert==1) {
            result.setCode(200);
        }else {
            result.setCode(202);
        }
        return result;
    }

    @ApiOperation(value = "按照用户真实姓名查询风险信息")
    @GetMapping("/findRiskInfoByRealName/{realName}")
    public Result findRiskInfoByRealName(@PathVariable String realName) {
        QueryWrapper<RiskInfo> qw = new QueryWrapper<>();
        qw.eq("realName", realName);
        List<RiskInfo> list = riskInfoDao.selectList(qw);
        riskInfoDao.updateTag(realName);
        return Result.ok(list);
    }

    @ApiOperation(value = "按照时间段查询风险信息")
    @GetMapping("/findRiskInfoByTime/{startTime}/{endTime}")
    public Result findRiskInfoByTime(@PathVariable(value = "startTime") String startTime,
                                     @PathVariable(value = "endTime") String endTime) {
        QueryWrapper<RiskInfo> qw = new QueryWrapper<>();
        qw.between("create_time", startTime, endTime);
        List<RiskInfo> list = riskInfoDao.selectList(qw);
        return Result.ok(list);
    }

    @ApiOperation(value = "查询未读风险信息")
    @GetMapping("/findRiskInfoTag")
    public Result findRiskInfoTag() {
        int count = riskInfoDao.findTagCount();
        return Result.ok(count);
    }

    /**
     * 文件上传
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "上传图片文件")
    @PostMapping("/sendInfoImage")
    public Msg fileUpload(@RequestParam("file") MultipartFile multipartFile) {
        Msg msg = new Msg();
        FileUtil fu = new FileUtil();
        // 获取图片的名字, 使用UUID重命名文件
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + fu.getSuffix(multipartFile.getOriginalFilename());
        if (!multipartFile.isEmpty()) {
            String savePath = uploadPath;
            try {
                FileUtil.uploadFile(multipartFile.getBytes(), savePath, fileName);
//                String path = "http://124.71.171.177:8080/api/worker/Info/" + fileName;
                String path = "https://www.emergencyfire.top/api/worker/Info/" + fileName;
                System.out.println(path);
                msg.setCode(0);
                msg.setMsg("success");
                msg.add("src", path);
                msg.add("title", fileName);
                return msg;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        msg.setCode(1);
        return msg;
    }

    @RequestMapping(path = "/Info/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        // 服务器存放路径
        fileName = uploadPath + "/" + fileName;
        // 文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("失败！！");
        }
    }

    @PostMapping("/adminSendInfo")
    public Result adminSendInfo(SendInfo sendInfo) {
        if(sendInfo.getContent()!=null){
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String time = df.format(new Date());
            sendInfo.setCreateTime(time);
            sendInfo.setAdminId(10);
            System.out.println(sendInfo);
            sendInfoDao.insert(sendInfo);
        }
        return Result.ok();
    }

//    @PostMapping("/admin5SendInfo")
//    public Result adminSendInfo(HttpServletRequest request, HttpServletResponse response) {
//        /* 允许跨域的主机地址 */
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        /* 允许跨域的请求方法GET, POST, HEAD 等 */
//        response.setHeader("Access-Control-Allow-Methods", "*");
//        /* 重新预检验跨域的缓存时间 (s) */
//        response.setHeader("Access-Control-Max-Age", "3600");
//        /* 允许跨域的请求头 */
//        response.setHeader("Access-Control-Allow-Headers", "*");
//        /* 是否携带cookie */
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("XDomainRequestAllowed", "1");
//        Map map = request.getParameterMap();
//        Set<String> set = map.keySet();
//        List<String> userIdList = new ArrayList<>();
//        List<SendInfo> sendInfoList = new ArrayList<>();
//
//        for(String name : set) {
//            String[] vals = (String[]) map.get(name);
//            String str1= StringUtils.join(vals, ",");
//            System.out.println(str1);
//
//            String[] split = str1.split(",");
//            for (int i = 0; i < split.length; i++) {
//                System.out.println(split[i]);
//                userIdList.add(split[i]);
//            }
//
//            if (name.equals("userId")){
//                for (int i=0;i<userIdList.size();i++){
//                    SendInfo sendInfo = new SendInfo();
//                    String replace = userIdList.get(i).replace(","," ");
//                    sendInfo.setUserId(Integer.parseInt(replace.trim()));
//                    sendInfoList.add(sendInfo);
//                }
//                break;
//            }
//        }
//
//        for(String name : set) {
//            String[] vals = (String[]) map.get(name);
//            for (int i=0;i<sendInfoList.size();i++){
//                if (name.equals("people")){
//                    for (String val : vals) {
//                        User user = userService.selectUserByrealName(val);
//                        sendInfoList.get(i).setAdminId(user.getUserId());
//                    }
//                }
//
//                if (name.equals("title")){
//                    for (String val : vals) {
//                        sendInfoList.get(i).setTitle(val);
//                        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        sendInfoList.get(i).setCreateTime(df.format(new Date()));
//
//                    }
//                }
//
//                if (name.equals("text")){
//                    for (String val : vals) {
//                        String content = Html2Text.removeHtmlTag(val);
//                        sendInfoList.get(i).setContent(content);
//                        List<String> imgUrl = Html2Text.getImgStr(val);
//                        sendInfoList.get(i).setImgUrl(imgUrl.toString());
//                    }
//                }
//            }
//        }
//        for (int i=0;i<sendInfoList.size();i++){
//            sendInfoDao.insert(sendInfoList.get(i));
//        }
//        return Result.ok();
//    }

    @PostMapping("/insert")
    public Result insert(Worker worker) {
        return workerService.insert(worker) ? Result.ok() : Result.fail();
    }

    @DeleteMapping("/delete/{workerId}")
    public Result delete(@PathVariable("workerId") int workerId) {
        return workerService.delete(workerId) ? Result.ok() : Result.fail();
    }

    @PutMapping("/update")
    public Result update(Worker worker) {
        return workerService.update(worker) ? Result.ok() : Result.fail();
    }

    @GetMapping("/select/{id}")
    public Result select(@PathVariable("id") int id) {
        return Result.ok(workerService.select(id));
    }

    @GetMapping("/selectPage")
    public TableMap selectPage(long page, long limit) {
        Page<Worker> workerPage = workerService.selectPage(page, limit);
        TableMap tableMap = new TableMap();
        tableMap.setData(workerPage.getRecords());
        tableMap.setCount(workerPage.getTotal());
        return tableMap;
    }

    @GetMapping("/selectPageByCondition")
    public TableMap selectPageByCondition(String startDate, String endDate) {
        return null;
    }

    @ApiOperation(value = "按时间导出")
    @GetMapping("/exportData/{startTime}/{endTime}")
    public void exportData(HttpServletResponse response,
                           @PathVariable("startTime") String startTime,
                           @PathVariable("endTime") String endTime) {
        try {
            workerService.exportDataByDate(response, startTime, endTime);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "巡更人员打卡签到")
    @GetMapping("/userClock/{userId}")
    public Result userClock(@PathVariable Integer userId) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(new Date());
        workerService.userClock(userId,time);

        String realName = userService.selectUserRealNameById(userId);
        DateFormat dfDetail = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String detailTime = dfDetail.format(new Date());
        workerService.addUserKQTJ(userId, realName, time, detailTime);
        return Result.ok();
    }

    @ApiOperation(value = "查询巡更人员今日是否打卡")
    @GetMapping("/findUserClock/{userId}")
    public Result findUserClock(@PathVariable Integer userId) {
        Result result = new Result();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(new Date());
        Integer userClock = workerService.findUserClock(userId, time);
        if (userClock==null){
            result.setCode(0);
        }else {
            result.setCode(1);
        }
        List<String> historyUserClock = workerService.findHistoryUserClock(userId);
        result.setData(historyUserClock);
        return result;
    }

    @ApiOperation(value = "导出所有风险点位信息", produces = "application/octet-stream")
    @GetMapping("/exportAllRiskPoints")
    public void exportAllRiskPoints(HttpServletResponse response) {
        try {
            workerService.exportAllRiskPoints(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "导出所有任务点位信息", produces = "application/octet-stream")
    @GetMapping("/exportAllTaskPoints")
    public void exportAllTaskPoints(HttpServletResponse response) {
        try {
            workerService.exportAllTaskPoints(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "根据时间导出所有漏查的任务点", produces = "application/octet-stream")
    @GetMapping("/exportAllLCTaskPoints")
    public void exportAllLCTaskPoints(HttpServletResponse response) {
        try {
            workerService.exportAllLCTaskPoints(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "巡更人员查询管理员消息")
    @GetMapping("/XGSelectInfo/{userId}")
    public Result XGSelectInfo(@PathVariable Integer userId) {
        List<SendInfo> list = workerService.selectInfo(userId);
        for (int i=0;i<list.size();i++){
            String s = userService.selectUserRealNameById(list.get(i).getAdminId());
            Map<String,Object> param = new HashMap<>();
            param.put("adminrealName",s);
            list.get(i).setParam(param);

            String imgUrl = list.get(i).getImgUrl();
            String replace1 = imgUrl.replace("[", "");
            String replace2 = replace1.replace("]", "");
            list.get(i).setImgUrl(replace2);
        }
        return Result.ok(list);
    }

    @ApiOperation(value = "人员数量统计表")
    @GetMapping("/XGUserNumExport/{startTime}/{endTime}")
    public Result XGUserNumExport(@PathVariable("startTime") String startTime,
                                  @PathVariable("endTime") String endTime) {
        List<Xgexport> list = workerService.XGUserNumExport(startTime, endTime);
        return Result.ok(list);
    }

    @ApiOperation(value = "人员数量统计表全查")
    @GetMapping("/XGUserNumExportQC")
    public Result XGUserNumExportQC() {
        List<Xgexport> list = workerService.XGUserNumExportQC();
        return Result.ok(list);
    }

    @ApiOperation(value = "任务点数量统计全查")
    @GetMapping("/RWNumExportQC")
    public Result RWNumExportQC() {
        List<Rwexport> list = workerService.RWNumExportQC();
        return Result.ok(list);
    }

    @ApiOperation(value = "任务点数量统计")
    @GetMapping("/RWNumExport/{startTime}/{endTime}")
    public Result RWNumExport(@PathVariable("startTime") String startTime,
                              @PathVariable("endTime") String endTime) {
        List<Rwexport> list = workerService.RWNumExport(startTime, endTime);
        return Result.ok(list);
    }

    @ApiOperation(value = "用户考勤统计全查")
    @GetMapping("/userKQExportQC")
    public Result userKQExportQC() {
        List<Userkq> list = workerService.userKQExportQC();
        return Result.ok(list);
    }

    @ApiOperation(value = "用户考勤统计")
    @GetMapping("/userKQExport/{startTime}/{endTime}")
    public Result userKQExport(@PathVariable("startTime") String startTime,
                               @PathVariable("endTime") String endTime) {
        List<Userkq> list = workerService.userKQExport(startTime,endTime);
        return Result.ok(list);
    }
}
